package com.dawson.happy;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    Handler updateHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                tvTitle.setText(title);
                int[] res = HappyNewYearWidget.getHappyTime(endTime);
                tvD.setText(String.valueOf(res[0]));
                tvH.setText(String.valueOf(res[1]));
                tvM.setText(String.valueOf(res[2]));
                tvS.setText(String.valueOf(res[3]));

                int color = HappyNewYearWidget.getWeekColor();
                tvTitle.setTextColor(color);
                tvD.setTextColor(color);
                tvH.setTextColor(color);
                tvM.setTextColor(color);
                tvS.setTextColor(color);


                //update widget
                updateWidget(res);

                updateHandler.sendMessageDelayed(updateHandler.obtainMessage(1), 1000);
            }
            return true;
        }
    });

    private TextView tvTitle, tvD, tvH, tvM, tvS;
    private EditText etTitle, etTime;
    private AppWidgetManager widgetManager;

    private String title = "";
    private long endTime = 0L;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒", Locale.CHINA);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main2);
        tvTitle = findViewById(R.id.widget_title);
        tvD = findViewById(R.id.widget_d);
        tvH = findViewById(R.id.widget_h);
        tvM = findViewById(R.id.widget_m);
        tvS = findViewById(R.id.widget_s);

        etTitle = findViewById(R.id.et_title);
        etTime = findViewById(R.id.et_time);

        etTime.setOnClickListener(v -> {
            tempSelectCalendar = Calendar.getInstance();
            tempSelectCalendar.setTimeInMillis(endTime);

            showDatePickerDialog();
        });

        findViewById(R.id.btn_save).setOnClickListener(v -> {
            String title = etTitle.getText().toString();
            if (TextUtils.isEmpty(title)) {
                Toast.makeText(MainActivity.this, "请填写标题", Toast.LENGTH_LONG).show();
                return;
            }
            if (title.length() > 24) {
                Toast.makeText(MainActivity.this, "标题太长", Toast.LENGTH_LONG).show();
                return;
            }
            long time = endTime;
            if (tempSelectCalendar != null) {
                time = tempSelectCalendar.getTimeInMillis();
            }
            if (time == 0L) {
                Toast.makeText(MainActivity.this, "请选择时间", Toast.LENGTH_LONG).show();
                return;
            }

            SharedPreferences sp = MainActivity.this.getSharedPreferences("dawson_sp", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("title", title);
            editor.putLong("end_time", time);
            editor.commit();

            MainActivity.this.title = title;
            endTime = time;

            updateHandler.sendMessage(updateHandler.obtainMessage(1));

            Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();

        });

        SharedPreferences sp = getSharedPreferences("dawson_sp", Context.MODE_PRIVATE);

        title = getString(R.string.appwidget_text);
        title = sp.getString("title", title);

        endTime = HappyNewYearWidget.END_DEFAULT;
        endTime = sp.getLong("end_time", endTime);

        etTitle.setText(title);
        etTime.setText(sdf.format(new Date(endTime)));

        widgetManager = AppWidgetManager.getInstance(this);

        updateHandler.sendMessage(updateHandler.obtainMessage(1));
    }

    private void updateWidget(int[] res) {
        // 更新widget的界面
        ComponentName name = new ComponentName(this.getPackageName(),
                "com.dawson.happy.HappyNewYearWidget");// 获取前面参数包下的后参数的Widget
        RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.happy_new_year_widget);

        HappyNewYearWidget.initRemoteView(this, views, title, res);

        widgetManager.updateAppWidget(name, views);//更新Widget
    }


    private Calendar tempSelectCalendar = null;

    private void showDatePickerDialog() {
        int year = tempSelectCalendar.get(Calendar.YEAR);
        int month = tempSelectCalendar.get(Calendar.MONTH);
        int day = tempSelectCalendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year1, monthOfYear, dayOfMonth) -> {
                    // 处理选择的日期（例如：更新UI显示）
                    tempSelectCalendar.set(year1, monthOfYear, dayOfMonth);
                    showTimePickerDialog();
                },
                year,
                month,
                day
        );

        datePickerDialog.show();
    }


    private void showTimePickerDialog() {
        final int year = tempSelectCalendar.get(Calendar.YEAR);
        final int month = tempSelectCalendar.get(Calendar.MONTH);
        final int day = tempSelectCalendar.get(Calendar.DAY_OF_MONTH);

        int h = tempSelectCalendar.get(Calendar.HOUR);
        int m = tempSelectCalendar.get(Calendar.MINUTE);

        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hour, minute) -> {
                    // 处理选择的日期（例如：更新UI显示）
                    tempSelectCalendar.set(year, month, day, hour, minute);
                    etTime.setText(sdf.format(tempSelectCalendar.getTime()));
                },
                h,
                m,
                true
        );

        timePickerDialog.show();
    }
}